import Cookies from 'js-cookie';
import CryptoJS from 'crypto-js';

export const reg = {
  init: /^[1-9]\d*$/, // 正整数
  phoneRegx: /^1[3456789]\d{9}$/, // 手机号
  number: /^[1-9]?[0-9]$|^20$/,
  profit: /^-?\d+(\.\d{1})?$/,
  big_num: /^[1-9]\d{0,4}$/,
  shop: /^(0-1|1-[1-3]|2-[1-3]|3-[1-3]|4-[1-3]|5-[1-4]|v-[1-2])$/
}

/* 重置Cookies */
export const moveCookies = (key, opt = {}) => {
  Cookies.remove(key, { expires: 10, ...opt });
};
export const setCookies = (key, value, opt = {}) => {
  Cookies.set(key, value, { expires: 10, ...opt });
};
export const getCookies = (key, opt = {}) => {
  return Cookies.get(key, { ...opt });
};

/*
  文件流下载文件
  flow 是后端给的文件流 blob
  fileName 是下载的文件名称
*/
export const streamingDownload = (res, filename, fileType = 'xlsx') => {
  const blob = new Blob([res]);
  const link = document.createElement('a');
  link.href = window.URL.createObjectURL(blob);
  //重命名文件
  link.download = `${filename}.${fileType}`;
  link.click();
  //释放内存
  window.URL.revokeObjectURL(link.href);
};

/* 密码加密_v5 */
export const PswToAesV5 = (psw) => {
  psw = psw.replace(/(^\s*)|(\s*$)/g, '');
  const m_psw = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(psw)).toString(); //需要加密的密码
  const key = CryptoJS.enc.Utf8.parse('EpNk90lAjm8SMy99');
  const iv = CryptoJS.enc.Utf8.parse('EpNk90lAjm8SMy99'); //16位初始向量
  const encrypted = CryptoJS.AES.encrypt(m_psw, key, {
    iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.ZeroPadding
  }).toString();
  return CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(encrypted)).toString();
};

export const getBrowserName = () => {
  var userAgent = navigator.userAgent, browserName = 'unknown'; // 初始化浏览器名称

  if (userAgent.indexOf("Firefox") > -1) {
    browserName = 'Firefox';
  } else if (userAgent.indexOf("OPR") > -1) {
    browserName = 'Opera';
  } else if (userAgent.indexOf("Chrome") > -1) {
    browserName = 'Chrome';
  } else if (userAgent.indexOf("Safari") > -1) {
    browserName = 'Safari';
  } else if (userAgent.indexOf("MSIE") > -1 || userAgent.indexOf("Trident") > -1) {
    browserName = 'Internet Explorer';
  }

  return browserName;
}